import 'package:flutter/material.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

import '../domain/UserVo.dart';

class AddFriendPage extends StatefulWidget {
  @override
  _AddFriendPageState createState() => _AddFriendPageState();
}

class _AddFriendPageState extends State<AddFriendPage> {

  List<UserVo> _matchedFriends = [];

  TextEditingController _searchController = TextEditingController();

  int _id;
  String _token;

  @override
  void initState() {
    SharedPreferences.getInstance().then((value) => {
      _id = value.getInt("id"), _token = value.getString("token")
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('添加好友'),
      ),
      body: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _searchController,
                    decoration: InputDecoration(
                      hintText: '搜索好友',
                    ),
                    onSubmitted: _trySearch,
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.search),
                  onPressed: () => _trySearch(_searchController.text),
                )
              ],
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: _matchedFriends.length,
              itemBuilder: (BuildContext context, int index) {
                final friend = _matchedFriends[index];
                return friend.id != _id ? ListTile(
                  title: Text(friend.userName),
                  trailing: ElevatedButton(
                    onPressed: () {
                      _addFriend(friend);
                    },
                    child: Text('添加'),
                  ),
                ) : SizedBox(height: 0);
              },
            ),
          ),
        ],
      ),
    );
  }

  void _addFriend(UserVo friend) async {
    // Add friend to the user's friend list
    print('Added friend: ${friend.id}');
    String meg = await addFriendRequest(context, _id, _token, friend.id); // 向服务器发送请求
    String notes = "";
    if (meg != null) {
      notes = "成功";
      // 添加双向好友im
      V2TimValueCallback<V2TimFriendOperationResult> addFriend = await TencentImSDKPlugin.v2TIMManager
          .getFriendshipManager().addFriend(userID: friend.id.toString() ,remark: friend.userName,
          addWording:"请求添加你为好友", addType:FriendTypeEnum.V2TIM_FRIEND_TYPE_BOTH);

    } else {
      notes = "失败";
    }
    showDialog<String>(context: context, builder: (BuildContext context) => AlertDialog(
      title: Text("提示"),
      content: Text("发送请求$notes"),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context, 'OK'),
          child: const Text('确认'),
        ),
      ],
    ));
  }

  void _trySearch (String text) async {
    _matchedFriends = await searchUserListRequest(context, text, _token);
    // 更新状态
    setState(() {
    });
  }
}
